// 引入子进程模块，用来执行其他命令或者软件
const { spawn } = require('child_process');

// 定义子进程模块的通用方法
class Process {
    constructor(cwd) {
        this.cwd = cwd;
    }
    run (command, params,callback){
        let process = spawn(command, params, {
            cwd : this.cwd
        });
        let logMessage = `${command} ${params[0]}`;
        let cmdMessage = '';

        console.log();
        console.log(`cwd：${this.cwd}`);
        console.log(logMessage);
        console.log();

        process.stdout.on('data', (data) => {
            if (!data) {
                console.error(`stderr: ${data}`);
            } else {
                cmdMessage = data.toString();
            }
        });
        process.stderr.on('data', (data) => {
            console.error(`stderr: ${data}`);
        });
        process.on('close', (data) => {
            if (data) {
                console.error(`stderr: ${data}`);
            } else {
                callback(cmdMessage);
            }
        });
    }
    asyncRun (command, params){
        return new Promise((resolve, reject) => {

            let process = spawn(command, params, {
                cwd : this.cwd
            });

            let logMessage = `${command} ${params.join(" ")}`;
            let cmdMessage = '';

            console.log();
            console.log(`cwd：${this.cwd}`);
            console.log(logMessage);
            console.log();

            process.stdout.on('data', (data) => {
                console.log("data"+data);
                if (!data) {
                    reject(`${logMessage} error1 : ${data}`);
                } else {
                    cmdMessage = data.toString();
                }
            });
            process.stderr.on('data', (data) => {
                console.error(`stderr: ${data}`);
            });
            process.on('close', (data) => {
                console.log("close"+data);
                if (data) {
                    reject(`${logMessage} error2 ! ${data}`);
                } else {
                    resolve(cmdMessage);
                }
            });
        })
    }
}
module.exports = Process;